﻿using DotNetExtensions.AspNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Svg;
using System.Drawing;
using DevExpressSimple.Properties;

namespace DevExpressSimple
{
    public class SvgCollection : Singleton<SvgCollection>
    {
        private readonly Dictionary<string, Bitmap> svgDict;
        private SvgCollection()
        {
            svgDict = new Dictionary<string, Bitmap>();
        }

        public void From(string path)
        {
            if (!Directory.Exists(path)) return;

            var files = Directory.GetFiles(path, "*.svg", SearchOption.AllDirectories);

            foreach (var item in files)
            {
                SvgBuilder builder = new SvgBuilder();
                string name = Path.GetFileNameWithoutExtension(item);
                var svg = builder.Open(new MemoryStream(File.ReadAllBytes(item)));
                Bitmap bitmap = svg.Draw();
                TryAdd(name, bitmap);
            }
        }


        public void TryAdd(string name, Bitmap value)
        {
            svgDict.AddOrUpdate(name, value);
        }

        public Bitmap TryGet(string name)
        {
            Bitmap value = null;
            if (svgDict.TryGetValue(name, out value)) return value;

            object obj = Resources.ResourceManager.GetObject(name);
            if (obj != null)
            {
                SvgBuilder builder = new SvgBuilder();
                var svg = builder.Open(new MemoryStream((byte[])obj));
                Bitmap bitmap = svg.Draw();
                TryAdd(name, bitmap);
            }
            return null;
        }
    }
}
